import { useCallback, useEffect, useState } from "react";
import useWords from "./useWords";
import useCountdownTimer from "./useCountdownTimer";
import useTyping from "./useTyping";
import { countErrors } from "../utils/helpers";
export type State = "start" | "typing" | "finish";
const useEngine = () => {
  const [state, setState] = useState<State>("start");
  const { timeLeft, resetCountdown, startCountdown } = useCountdownTimer(60);
  const { typed, cursor, clearTyped, totalTyped, resetTotalTyped } = useTyping(
    state != "finish"
  );
  const [errors, setErrors] = useState(0);
  const { words, updateWords } = useWords(10);

  const areWordsFinished = cursor == words.length;

  const restart = () => {
    resetCountdown();
    resetTotalTyped();
    setState("start");
    updateWords();
    clearTyped();
    setErrors(0);
  };

  const sumErrors = useCallback(() => {
    const wordsReached = words.substring(0, Math.min(words.length, cursor));
    setErrors((prevErrors) => prevErrors + countErrors(typed, wordsReached));
  }, [typed, words, cursor]);

  // 开始敲击
  useEffect(() => {
    if (state === "start" && cursor > 0) {
      setState("typing");
      startCountdown();
    }
  }, [state, startCountdown, cursor]);

  // 计时结束
  useEffect(() => {
    if (timeLeft == 0 && state == "typing") {
      setState("finish");
      sumErrors();
    }
  }, [timeLeft, state, sumErrors]);

  // 敲完了
  useEffect(() => {
    if (areWordsFinished) {
      updateWords();
      clearTyped();
      sumErrors();
    }
  });

  return {
    state,
    words,
    updateWords,
    timeLeft,
    typed,
    errors,
    totalTyped,
    clearTyped,
    startCountdown,
    resetCountdown,
    restart,
  };
};

export default useEngine;
